<template>
  <CDialog
    :title="type == 'MODEL' ? '替换为子模型数据' : '替换为供应商数据集'"
    size="large"
    v-model:visible="dialogVisible"
    @confirm="handleConfirm"
    @cancel="dialogVisible = false"
    :loading="loading"
    :footer="false"
  >
    <div class="header">
      <div>
        <el-input
          class="header-input"
          placeholder="零部件编码"
          v-model="searchForm.productCode"
          @input="handleRefresh"
          clearable
        >
          <template #suffix>
            <CIcon type="c-xian-sousuo"></CIcon>
          </template>
        </el-input>
        <el-input
          class="header-input g-ml8"
          placeholder="零部件名称"
          v-model="searchForm.productName"
          @input="handleRefresh"
          type="text"
          clearable
        >
          <template #suffix>
            <CIcon type="c-xian-sousuo"></CIcon>
          </template>
        </el-input>
        <el-input
          v-if="type == 'SUPPLIER'"
          class="header-input g-ml8"
          placeholder="同类编码"
          v-model="searchForm.queryPartSuitCode"
          @input="handleRefresh"
          type="text"
          clearable
        >
        </el-input>
      </div>

      <div id="factor-simple-page"></div>
    </div>
    <div class="replace-dialog-body">
      <CTable
        class="replace-dialog-table"
        :pagination="{
          teleport: '#factor-simple-page',
          layout: 'total, prev, slot, next'
        }"
        :loadData="loadData"
        ref="tableRef"
      >
        <vxe-column title="零部件名称" min-width="200" show-overflow="tooltip">
          <template #default="scope">
            <CLink @click="handleOpenSiteData(scope.row)">{{
              empty(scope.row.modelName || scope.row.partName)
            }}</CLink>
          </template>
        </vxe-column>
        <vxe-column title="零部件编码" min-width="210" show-overflow="tooltip">
          <template #default="scope">
            <span>{{ empty(scope.row.modelCode || scope.row.partCode) }}</span>
            <el-popover
              placement="bottom"
              width="300"
              v-if="scope.row.partSuitCode && scope.row.partSuitCode.length"
            >
              <template #reference>
                <CIcon type="c-xian-gengduoxinxi" class="more-icon"></CIcon>
              </template>
              <div class="g-font-14n1 g-mb4">同类编码：</div>
              <div class="model-tag-wrap">
                <div class="model-tag" v-for="(item, index) in scope.row.partSuitCode" :key="index">
                  {{ item }}
                </div>
              </div>
            </el-popover>
          </template>
        </vxe-column>
        <vxe-column title="数据年份" width="100" show-overflow="tooltip">
          <template #default="scope">
            <p v-ellTooltip>{{ scope.row.accountYear || scope.row.dataYear }}</p>
          </template>
        </vxe-column>
        <vxe-column title="提交人/时间" width="160" show-overflow="tooltip">
          <template #default="scope">
            <CTableColumn
              :main-text="scope.row.submitBy || scope.row.submitter"
              :sub-text="scope.row.submitTime"
            ></CTableColumn>
          </template>
        </vxe-column>
        <vxe-column title="操作" width="80">
          <template #default="scope">
            <CTableButtonGroup :buttons-config="getTableButtonsConfig(scope.row)" />
          </template>
        </vxe-column>
      </CTable>
    </div>
    <SiteDataDialog
      :title="siteDataModelName"
      v-model:visible="siteDataVisible"
      :modelNo="siteDataModelNo"
      :nodeCode="nodeCode"
      @replace="handleReplace"
      :loading="loading"
      :type="type"
    ></SiteDataDialog>
    <SupplierFactorDialog
      v-model:visible="supplierFactorDialogVisible"
      :nodeNo="nodeNo"
      :formNo="siteDataModelNo"
      :readonly="false"
      :title="siteDataModelName"
      :nodeCode="nodeCode"
      @refresh="handleReplace"
    ></SupplierFactorDialog>
  </CDialog>
</template>

<script lang="ts" setup name="ReplaceDialog">
import { defineProps, defineEmits, computed, reactive, withDefaults, ref, watch } from 'vue'
import { CDialog } from '@/components/CDialog'
import { CTable } from '@/components/CTable'
import { CLink } from '@/components/CLink'
import { GIcon } from '@/components/GIcon/index'
import { empty } from '@/utils/index'
import type { BasicPagingListParams } from '@/apis/basicModel'
import type { TableButtonItem } from '@/components/CTable'
import { CTableColumn, CTableButtonGroup } from '@/components/CTable'
import SiteDataDialog from '../SiteDataDialog/index.vue'
import SupplierFactorDialog from '../SupplierFactorDialog/index.vue'
import {
  getPageItemModel,
  postReplaceModel,
  getFormList,
  postReplaceForm
} from '@/apis/pcf/myModel/modelDetail'
import type {
  GetPageItemFormParams,
  GetPageItemModelParams
} from '@/apis/pcf/myModel/model/modelDetailModel'
import { useMessage } from '@/hooks/useMessage'
import { replaceForm } from '@/apis/pcf/supplier/supplierList'
import { DataSourceEnum } from '@/constants/pcf'

import { debounce } from 'lodash'
interface ReplaceDialogProps {
  nodeNo: string
  modelNo: string
  supplierNo: string
  partCode?: string
  visible: boolean
  /**
   * MODEL 替换为子模型  SUPPLIER 替换为供应商数据集
   */
  type: 'MODEL' | 'SUPPLIER'
}

const props = withDefaults(defineProps<ReplaceDialogProps>(), {
  type: 'MODEL'
})
const emits = defineEmits(['update:visible', 'refresh'])

const dialogVisible = computed({
  get: () => {
    return props.visible
  },
  set: (value: boolean) => {
    emits('update:visible', value)
  }
})
watch(
  () => dialogVisible.value,
  (val) => {
    if (val && props.partCode) {
      searchForm.productCode = props.partCode
    } else {
      searchForm.productCode = ''
      searchForm.productName = ''
    }
  }
)
const tableRef = ref()
const { createMessage } = useMessage()
const loading = ref(false)
const nodeCode = ref('')

function loadData(parameter: BasicPagingListParams) {
  if (props.type == 'MODEL') {
    console.log('parameter', parameter)
    const params = {
      productCode: searchForm.productCode,
      productName: searchForm.productName,
      excludeModelNo: props.modelNo
    }
    Object.assign(params, parameter)

    return getPageItemModel(params)
  } else {
    const params = {
      partCode: searchForm.productCode,
      partName: searchForm.productName,
      supplierNo: props.supplierNo,
      queryPartSuitCode: searchForm?.queryPartSuitCode
    }
    Object.assign(params, parameter)
    return getFormList(params)
  }
}

function handleConfirm() {
  console.log('handleConfirm')
}

function getTableButtonsConfig(row: any): TableButtonItem[] {
  return [
    {
      text: '替换',
      onClick: () => handleClick(row)
    }
  ]
}

function handleClick(row: any) {
  console.log('handleClick', row)
  postReplaceModelReq(props.type == 'MODEL' ? row.modelNo : row.formNo)
}
const searchForm = reactive({
  productCode: '',
  productName: '',
  queryPartSuitCode: ''
})

const siteDataVisible = ref(false)
const supplierFactorDialogVisible = ref(false)
const siteDataModelNo = ref('')
const siteDataModelName = ref('')
function handleOpenSiteData(row: any) {
  if (row.feedbackType == 'CERTIFICATION_REPORT') {
    // 显示报告因子
    supplierFactorDialogVisible.value = true
    siteDataModelName.value = row.partName
    nodeCode.value = row.partCode
    siteDataModelNo.value = row.formNo
  } else {
    if (props.type == 'MODEL') {
      siteDataModelNo.value = row.modelNo
      siteDataModelName.value = row.modelName
      nodeCode.value = row.modelCode
      siteDataVisible.value = true
    } else {
      siteDataModelNo.value = row.formNo
      siteDataModelName.value = row.partName
      nodeCode.value = row.partCode
      siteDataVisible.value = true
    }
  }
}

const handleReplace = () => {
  postReplaceModelReq(siteDataModelNo.value, true)
}
async function postReplaceModelReq(modelNo: string, closeSiteDataDialog = false) {
  try {
    loading.value = true
    if (props.type == 'MODEL') {
      await postReplaceModel(props.nodeNo, modelNo)
    } else {
      await replaceForm(props.nodeNo, modelNo)
    }
    createMessage.success('替换成功！')
    emits('refresh', props.nodeNo)
    dialogVisible.value = false
    closeSiteDataDialog && (siteDataVisible.value = false)
    loading.value = false
  } catch (error) {
    console.log('error', error)
    loading.value = false
  }
}

const handleRefresh = debounce(() => {
  tableRef.value?.refresh()
}, 300)
</script>

<style lang="scss" scoped>
.header {
  margin-bottom: 14px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .header-input {
    width: 192px;
  }
}
.replace-dialog-body {
  :deep(.vxe-table) {
    margin-bottom: 24px;
  }
}
.model-tag {
  min-width: 36px;
  height: 20px;
  padding: 0 6px;
  line-height: 20px;
  text-align: center;
  background: #eef1f5;
  border-radius: 3px;
  font-size: 12px;
  color: #5a739a;
  margin-bottom: 4px;
  margin-right: 4px;
}
.model-tag-wrap {
  display: flex;
  flex-wrap: wrap;
}
.more-icon {
  margin-left: 4px;
  font-size: 12px;
  color: #96a7b3;
  cursor: pointer;
}
</style>
